import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { ListBaseClass } from '@shared/classes/ListBaseClass'
import { IReportSetting, IReportReleaseRecord, ReportTypeMap, ReportLevelMap, EReportLevel } from '@shared/interfaces/report'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { I18NService } from '@core'
import { Router, ActivatedRoute } from '@angular/router'
import { SettingsService } from '@delon/theme'
import { DataService } from '@shared/services/data.service'
import { ACLService } from '@delon/acl'
import { ISearchSchema, ISearchOption } from '@shared/interfaces/search'
import { STColumn } from '@delon/abc'
import { ESearchType, EReportType } from '@shared/enums'
import { PublicService } from '@shared/services/public.service'
import { ReportService } from '../report.abstract.service'
import { openDownloadDialog } from 'app/utils/helpers'
import { today } from 'app/utils/contraints'
import { take } from 'rxjs/operators'
import { EDateLimitEnum } from '@shared/interfaces/common'

@Component({
  selector: 'app-report-download',
  templateUrl: './download.component.html',
  styleUrls: ['../../../shared/styles/table.less'],
})
export class ReportDownloadComponent extends ListBaseClass<IReportSetting, IReportSetting> implements OnInit {

  data: IReportSetting[] = []

  @ViewChild('tplAcquirer') tplAcquirer: TemplateRef<void>
  @ViewChild('tplGroup') tplGroup: TemplateRef<void>
  @ViewChild('tplMerchant') tplMerchant: TemplateRef<void>
  @ViewChild('tplStore') tplStore: TemplateRef<void>

  searchSchema: ISearchSchema[] = []

  columns: STColumn[] = []

  constructor(
    public msg: NzMessageService,
    public i18n: I18NService,
    public router: Router,
    public route: ActivatedRoute,
    public settings: SettingsService,
    private dataService: DataService,
    private modal: NzModalService,
    public aclService: ACLService,
    private publicService: PublicService,
    private reportService: ReportService,
  ) {
    super(msg, i18n, route, router, settings)
  }

  ngOnInit() {
    this.initColumns()
    this.generateSearchSchema()
    this.parseParams().subscribe(() => {
      this.queryTableDataWithParams()
    })
    this.initialAAMSFilter()
  }

  initColumns(): void {
    const canDownload = this.aclService.canAbility('api.post.camel.report.download')
    this.columns = [
      {
        title: '报表代码',
        i18n: 'REPORT.CODE',
        index: 'rptCd',
        width: '120px',
        className: 'text-center',
        fixed: 'left',
      },
      {
        title: '报表名称',
        i18n: 'REPORT.NAME',
        index: 'rptName',
        width: '200px',
        className: 'text-left',
      },
      {
        title: '报表类型',
        i18n: 'REPORT.TYPE',
        index: 'rptType',
        width: '100px',
        className: 'text-center',
        render: 'type'
      },
      {
        title: '文件格式',
        i18n: 'REPORT.FILETYPE',
        index: 'rptFmt',
        width: '100px',
        className: 'text-center',
      },
      {
        title: '报表层级',
        i18n: 'REPORT.BIZLEVEL',
        index: 'rptLevel',
        width: '100px',
        className: 'text-center',
        render: 'level',
      },
      {
        title: '层级编号',
        i18n: 'REPORT.BIZCODE',
        index: 'rptLevelCode',
        width: '200px',
        className: 'text-center',
      },
      {
        title: '层级名称',
        i18n: 'REPORT.BIZNAME',
        index: 'rptLevelName',
        width: '200px',
        className: 'text-center',
      },
      {
        title: '生成时间',
        i18n: 'REPORT.CREATETIME',
        index: 'rptCreateTime',
        width: '150px',
        type: 'date',
        className: 'text-center',
      },
      {
        title: '操作',
        i18n: 'GENERAL.INFO.OPERATION',
        width: '200px',
        fixed: 'right',
        className: 'text-center p-xs',
        iif: () => canDownload,
        buttons: [
          {
            text: '',
            click: this.download.bind(this),
            icon: {
              iconfont: 'icon-download-twotone',
              type: 'iconfont',
            },
            iif: () => canDownload,
          }
        ]
      }
    ]
  }

  generateSearchSchema(): void {
    this.searchSchema = [
      {
        label: 'GENERAL.INFO.CREATED_AT',
        labelI18n: 'GENERAL.INFO.CREATED_AT',
        index: ['submittedAtFrom', 'submittedAtTo'],
        type: ESearchType.dateRange,
        dateLimitType: EDateLimitEnum.Month,
        value: [today, today],
      },
      {
        label: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        labelI18n: 'GENERAL.BIZ_LEVEL.INSTITUTION',
        index: 'insCode',
        component: this.tplAcquirer,
        customFunc: () => this.selectedAcquirer && this.selectedAcquirer.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.AGENT',
        labelI18n: 'GENERAL.BIZ_LEVEL.AGENT',
        index: 'agentCode',
        component: this.tplGroup,
        customFunc: () => this.selectedGroup && this.selectedGroup.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.MERCHANT',
        labelI18n: 'GENERAL.BIZ_LEVEL.MERCHANT',
        index: 'intMerCode',
        component: this.tplMerchant,
        customFunc: () => this.selectedMerchant && this.selectedMerchant.code,
      },
      {
        label: 'GENERAL.BIZ_LEVEL.STORE',
        labelI18n: 'GENERAL.BIZ_LEVEL.STORE',
        index: 'intStoreCode',
        component: this.tplStore,
        customFunc: () => this.selectedStore && this.selectedStore.code,
      },
      {
        label: '报表代码',
        labelI18n: 'REPORT.CODE',
        index: 'rptCd',
        type: ESearchType.input,
      },
      {
        label: '报表名称',
        labelI18n: 'REPORT.NAME',
        index: 'rptName',
        type: ESearchType.input,
      },
      {
        label: '报表类型',
        labelI18n: 'REPORT.TYPE',
        index: 'rptType',
        type: ESearchType.selection,
        options: this.genReportTypeOptions(),
      },
    ]
  }

  download(record: IReportReleaseRecord): void {
    const { rptKey } = record
    this.reportService.downloadReport(rptKey).pipe(take(1)).subscribe(
      data => {
        const { url } = data
        openDownloadDialog(url, '下载报表')
      }
    )
  }

  parseType(type: EReportType): string {
    return this.trans(ReportTypeMap[type])
  }

  parseLevel(level: EReportLevel): string {
    return this.trans(ReportLevelMap[level])
  }

  initialAAMSFilter(): void {
    this.initAcquirer()
    this.initAgent()
    this.initMerchant()
    this.initStore()
  }

  genReportTypeOptions(): ISearchOption[] {
    return this.publicService.genOptions(ReportTypeMap)
  }

  queryTableDataWithParams(): void {
    this.loading = true
    this.reportService
      .getReleaseList(this.params)
      .subscribe(this.renderList.bind(this))
  }

}
